﻿using Newtonsoft.Json;

namespace vztools;

class Program
{
    static void Main(string[] args)
    {
        List<string> argsList = Utils.GetArgsList(args);
        Console.OutputEncoding = System.Text.Encoding.UTF8;
        
        Config? config = GetConfig();
        if(config == null)
        {
            Utils.WriteLine("Error: config.json is invalid", ConsoleColor.Red);
            return ;
        }

        ScriptManager manager = new ScriptManager(config);

        if(argsList.Count == 0)
        {
            manager.ShowScriptsAndHelp();
            return;
        }

        if(manager.OpenScriptsDirectory(argsList))
            return;

        if(manager.CreateNewScript(argsList))
            return;

        if(manager.ImportScripts(argsList))
            return;

        manager.FindAndRunScript(argsList);
    }

    private static Config? GetConfig()
    {
        Config? config = null;
        string appPath = AppDomain.CurrentDomain.BaseDirectory;
        string configPath = Path.Join(appPath, "config.json");
        if(!File.Exists(configPath))
        {
            string scriptsDir = Path.Join(appPath, "Scripts");
            config = new Config(){ScriptDirectory = scriptsDir};
            File.WriteAllText(configPath, JsonConvert.SerializeObject(config, Formatting.Indented)); 
        }
        else
        {
            string configStr = File.ReadAllText(configPath);
            config = JsonConvert.DeserializeObject<Config>(configStr);
        }
        
        return config;
    }
    
}
